2019-1-16 Stream流的学习

1
Arrays.stream(new int[] {1, 2, 3}).map(n -> 2 * n + 1).average().ifPresent(System.out::println);

或者更加简洁的是

1
Arrays.stream(new int[] {1, 2, 3}).map(n -> 2 * n + 1).average().ifPresent(x -> System.out.println(x));

原本的样子是:

1
2
3
4
5
6
7
8
long sum = 0;
long count = 0;
for (int n : new int[]{1, 2, 3}) {
int i = 2 * n + 1;
sum += i;
count++;
}
(count > 0 ? OptionalDouble.of((double) sum / count) : OptionalDouble.empty()).ifPresent(System.out::println);

1
2
3
4
5
6
7
Stream.of("a1", "a2", "a3")
.map(x -> x.substring(1))
.mapToInt(Integer::parseInt)
.max()
.ifPresent(n -> System.out.println(n));

结果为3

substring的用法:

public String substring(int beginIndex)
beginIndex – 起始索引(包括), 索引从 0 开始。

public String substring(int beginIndex, int endIndex)
endIndex – 结束索引(不包括)。

所以可以看出上面的代码通过substring方法因为只有其实索引所以结果为 a2,a3
然后MapToInt后得到 2,3 通过max方法得到3 然后通过最后的ifPreset判断打印出结果3

1
2
3
4
IntStream.range(1,4)
.mapToObj(i -> "a" + i)
.forEach(x -> System.out.println(x));
SpringApplication.run(DemoApplication.class, args);

可以理解为

1
2
3
range(1,4)
等价于
for(int i = 1;i < 4 ; i++)

1
2
3
4
5
6
Stream.of(1.0, 2.0, 3.0)
.mapToInt(Double::intValue)
.mapToObj(i -> "a" + i)
.forEach(x -> System.out.println(x));

结果为a1 a2 a3

中间操作的惰性

1
2
3
4
5
6
Stream<Integer> sorted = Stream.of(1, 2, 3, 4, 5)
.sorted((i1,i2)-> {
System.out.println(i1);
return i1;
}
);

1
2
3
4
5
Stream.of("d2", "a2", "b1", "b3", "c")
.filter(s -> {
System.out.println("filter: " + s);
return true;
});
1
2
3
4
5
Stream.of("d2", "a2", "b1", "b3", "c")
.map(s -> {
System.out.println("map: " + s);
return s.toUpperCase();
})

有关于java短路和非短路操作的详细介绍文章参考

https://users.drew.edu/bburd/JavaForDummies6/shortCircuitEval.pdf
https://stackoverflow.com/questions/18349330/short-circuit-vs-non-short-circuit-operators/18349426
https://stackoverflow.com/questions/7101992/why-do-we-usually-use-not-what-is-the-difference
https://stackoverflow.com/questions/8759868/java-logical-operator-short-circuiting
https://stackoverflow.com/questions/9264897/reason-for-the-existence-of-non-short-circuit-logical-operators

Optional类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import java.util.Optional;

public class Java8Tester {
public static void main(String args[]){

Java8Tester java8Tester = new Java8Tester();
Integer value1 = null;
Integer value2 = new Integer(10);

// Optional.ofNullable - 允许传递为 null 参数
Optional<Integer> a = Optional.ofNullable(value1);

// Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
Optional<Integer> b = Optional.of(value2);
System.out.println(java8Tester.sum(a,b));
}

public Integer sum(Optional<Integer> a, Optional<Integer> b){

// Optional.isPresent - 判断值是否存在

System.out.println("第一个参数值存在: " + a.isPresent());
System.out.println("第二个参数值存在: " + b.isPresent());

// Optional.orElse - 如果值存在,返回它,否则返回默认值
Integer value1 = a.orElse(new Integer(0));

//Optional.get - 获取值,值需要存在
Integer value2 = b.get();
return value1 + value2;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
String strA = " abcd ", strB = null;
print(strA);
print("");
print(strB);
getLength(strA);
getLength("");
getLength(strB);
public static void print(String text) {
// Java 8
Optional.ofNullable(text).ifPresent(System.out::println);
// Pre-Java 8
if (text != null) {
System.out.println(text);
}
}
public static int getLength(String text) {
// Java 8
return Optional.ofNullable(text).map(String::length).orElse(-1);
// Pre-Java 8
// return if (text != null) ? text.length() : -1;
};

很重要的Java学习路线介绍

http://www.zuoxiaolong.com/html/article_287.html

先过滤再排序再转类型尽量减少操作步骤性能

由于流的在执行了终端操作后就会不能复用所以会导致如下的代码的问题

1
2
3
4
5
6
7
8
9
10
Stream<String> stream = Stream.of("a1","b1","c","d")
.filter(s -> s.startsWith("b"));

stream.anyMatch(s -> true);
stream.noneMatch(s -> true);

>>> Exception in thread "main" java.lang.IllegalStateException: stream has already been operated upon or closed
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:229)
at java.util.stream.ReferencePipeline.noneMatch(ReferencePipeline.java:459)
at com.example.demo.DemoApplication.main(DemoApplication.java:58)